<template>
  <ContentDetailWrap :title="titleObj[RouteType]" @back="push('/system/menuManage')">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      :disabled="RouteType === 2"
      label-width="140px"
    >
      <el-form-item :label="t('menuDetail.type')" prop="type">
        <el-radio-group v-model="ruleForm.menuType">
          <el-radio :label="0">{{ t('menuDetail.menu1') }}</el-radio>
          <el-radio :label="1">{{ t('menuDetail.menus') }}</el-radio>
          <el-radio :label="2">{{ t('menuDetail.limitBtn') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="ruleForm.menuType === 2 ? t('menuDetail.limitBtn') : t('menuDetail.name')"
        prop="name"
      >
        <el-input
          v-model="ruleForm.name"
          :placeholder="
            ruleMsg(ruleForm.menuType === 2 ? t('menuDetail.limitBtn') : t('menuDetail.name'))
          "
        />
      </el-form-item>
      <!-- 子菜单 -->
      <el-form-item
        :label="t('menuDetail.parentId')"
        v-if="ruleForm.menuType !== 0"
        prop="parentId"
      >
        <el-tree-select
          v-model="ruleForm.parentId"
          :data="treeAllData"
          :placeholder="ruleMsg(t('menuDetail.parentId'))"
          check-strictly
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item :label="t('menuDetail.path')" prop="url">
        <el-input v-model="ruleForm.url" :placeholder="ruleMsg(t('menuDetail.path'))" />
      </el-form-item>
      <el-form-item :label="t('menuDetail.component')" prop="component">
        <el-input v-model="ruleForm.component" :placeholder="ruleMsg(t('menuDetail.component'))" />
      </el-form-item>
      <template v-if="ruleForm.menuType !== 2">
        <el-form-item :label="t('menuDetail.link')" v-show="ruleForm.menuType === 0">
          <el-input v-model="ruleForm.redirect" :placeholder="ruleMsg(t('menuDetail.redirect'))" />
        </el-form-item>
        <el-form-item :label="t('menuDetail.icon')">
          <SelectIcon v-model:iconValue="ruleForm.icon" />
          <!-- <el-input v-model="ruleForm.icon" :placeholder="ruleMsg(t('menuDetail.icon'))" /> -->
        </el-form-item>
        <el-form-item :label="t('menuDetail.sortNo')">
          <el-input-number v-model="ruleForm.sortNo" :precision="2" controls-position="right" />
        </el-form-item>
        <!-- <el-form-item :label="t('menuDetail.route')">
          <el-switch v-model="ruleForm.route" inline-prompt active-text="是" inactive-text="否" />
        </el-form-item> -->
        <el-form-item :label="t('menuDetail.hidden')">
          <el-switch v-model="ruleForm.hidden" inline-prompt active-text="是" inactive-text="否" />
        </el-form-item>
        <el-form-item :label="t('menuDetail.leaf')">
          <el-switch
            v-model="ruleForm.leaf"
            inline-prompt
            active-text="外部"
            inactive-text="内部"
          />
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item :label="t('menuDetail.perms')" prop="perms">
          <el-input v-model="ruleForm.perms" :placeholder="ruleMsg(t('menuDetail.placePerms'))" />
        </el-form-item>
        <el-form-item :label="t('menuDetail.permsType')">
          <el-radio-group v-model="ruleForm.permsType">
            <el-radio label="1">{{ t('menuDetail.permsType1') }}</el-radio>
            <el-radio label="2">{{ t('menuDetail.permsType2') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="t('menuDetail.status')">
          <el-radio-group v-model="ruleForm.status">
            <el-radio label="0">{{ t('menuDetail.statusoff') }}</el-radio>
            <el-radio label="1">{{ t('menuDetail.statusopen') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
      <!-- <el-form-item v-if="RouteType !== 2">
        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
        <el-button type="primary" @click="disableForm(ruleFormRef)">Create</el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item> -->
    </el-form>

    <template #right v-if="RouteType !== 2">
      <ElButton type="primary" :loading="loading" @click="submitForm(ruleFormRef)">
        {{ t('exampleDemo.save') }}
      </ElButton>
    </template>
  </ContentDetailWrap>
</template>
<script setup lang="ts">
// import Write from './Write.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElButton } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter, useRoute } from 'vue-router'
import {
  // duplicateCheck,
  getMenuTableTreeApi,
  addPermission,
  editPermission
} from '@/api/modules/menu'
import SelectIcon from '@/views/System/components/SelectIcon/index.vue'
// import { checkPhoneNumber } from '@/utils/eleValidate'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const { t } = useI18n()
const { query } = useRoute()
const ruleForm = ref<{ [key: string]: any }>({
  menuType: Number(query.type === '3' ? '2' : '0'),
  id: '',
  name: '', // 菜单名称
  url: '', // 菜单路径
  component: '', // 前端组件
  redirect: '', // 默认跳转地址
  icon: '', // 图标
  sortNo: 1, // 排序
  leaf: false, // 打开方式
  route: true, // 隐藏路由
  hidden: false, // 隐藏路由
  parentId: '', // 上级菜单
  perms: '', // 授权标识 - 按钮
  permsType: '', // 授权策略 - 按钮
  status: '' // 状态 - 按钮
})
// form 赋值
if (query.row) {
  const data = new Function('return (' + decodeURIComponent(query.row as any) + ')')()
  Object.keys(ruleForm.value).forEach((key) => {
    ruleForm.value[key] = data[key]
  })
}
onMounted(() => {
  getLoadTree()
})
const titleObj = [t('titObj.add'), t('titObj.edit'), t('titObj.det'), t('titObj.alow')]
const RouteType: any = computed(() => Number(query.type))
const ruleFormRef = ref<FormInstance>()
// 监听type 修改校验规则
watch(
  () => ruleForm.value.menuType,
  (val) => {
    // @ts-expect-error
    rules.name[0].message = ruleMsg(
      ruleForm.value.menuType === 2 ? t('menuDetail.limitBtn') : t('menuDetail.name')
    )
    // @ts-expect-error
    rules.url[0].required = !Boolean(val === 2)
  }
)
const { push } = useRouter()

const loading = ref(false)
// el-tree 数据
const treeAllData = ref<{ [key: string]: any }[]>([])
// 获取权限树
const getLoadTree = async () => {
  const {
    result: { treeList }
  } = await getMenuTableTreeApi()
  treeAllData.value = treeList
}
// 校验表单
const ruleMsg = (text) => t('menuDetail.place') + text
const rules = reactive<FormRules>({
  name: [
    {
      required: true,
      message: ruleMsg(
        ruleForm.value.menuType === 2 ? t('menuDetail.limitBtn') : t('menuDetail.name')
      ),
      trigger: 'blur'
    },
    { min: 1, max: 255, message: '长度应为1到255', trigger: 'blur' }
  ],
  parentId: [{ required: true, message: ruleMsg(t('menuDetail.parentId')), trigger: 'blur' }],
  url: [
    { required: true, message: ruleMsg(t('menuDetail.path')), trigger: 'blur' },
    { min: 2, max: 255, message: '长度应为2到255', trigger: 'blur' }
  ],
  component: [
    { required: true, message: ruleMsg(t('menuDetail.component')), trigger: 'blur' },
    { min: 1, max: 255, message: '长度应为2到255', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: ruleMsg(t('menuDetail.icon')), trigger: 'change' },
    { min: 2, max: 255, message: '长度应为2到255', trigger: 'blur' }
  ],
  perms: [
    // { required: false, message: '请输入授权标识!', validator: validatePerms, trigger: 'blur' },
    { required: false, message: '请输入授权标识!', trigger: 'blur' },
    { min: 2, max: 255, message: '长度应为2到255', trigger: 'blur' }
  ]
  // desc: [{ required: true, message: 'Please input activity form', trigger: 'blur' }]
})
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res: any
      // if (ruleForm.value.menuType && !ruleForm.value.parentId) {
      //   ElMessage.error('请选择上级菜单')
      //   return
      // }
      if (RouteType.value === 1) {
        // 编辑
        res = await editPermission(ruleForm.value)
      } else {
        // 新增
        res = await addPermission(ruleForm.value)
      }
      if (res.success) {
        ElMessage.success(res.message)
        push('/system/menuManage')
      } else {
        ElMessage.error(res.message)
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>
